package naga.x.net;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import naga.x.common.Updatable;

public class SessionUpdater implements Updatable, Runnable, SessionObserver {
	
	private Executor executor;
	private Map<Long, Session> sessions;
	
	public SessionUpdater(final int id) {
		executor = Executors.newFixedThreadPool(1, new ThreadFactory() {
			@Override
			public Thread newThread(Runnable r) {
				Thread t = new Thread(r, "SessionUpdater-" + id);
				t.setDaemon(true);
				return t;
			}
		});
		sessions = new ConcurrentHashMap<Long, Session>(64);
	}
	
	@Override
	public void fireSessionCreated(Session session) {
		sessions.put(session.getId(), session);
	}
	
	@Override
	public void fireSessionClosed(Session session) {
		sessions.remove(session.getId());
	}

	@Override
	public boolean update() {
		executor.execute(this);
		return true;
	}

	@Override
	public void run() {
		Iterator<Session> itr = sessions.values().iterator();
		while (itr.hasNext()) {
			Session session = itr.next();
			if (session == null || !session.update()) {
				itr.remove();
			}
		}
	}
	

}
